<!-- 销售订单修改界面 -->
<template>
    <!--基本信息-->
    <div class="white-container">
        <h3 style="text-align: left;margin-left: 20px;padding-top: 20px;">基础信息</h3>
        <hr style="border:1px solid #ccd0d4;"/>
        <el-form :model="saleform" :rules="rules" ref="saleref" style="margin-top: 20px;margin-left: 50px;" label-width="auto">
            <el-row>
                <el-col :span="11">
                    <el-form-item label="销售单号" prop="code">
                        <el-input placeholder="自动获取编号" style="width: 300px;" v-model="saleform.code" disabled></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item label="销售日期" prop="date">
                        <el-date-picker
                            v-model="saleform.date"
                            type="datetime"
                            placeholder="请选择"
                            format="YYYY-MM-DD HH:mm:ss"
                            date-format="MMM DD, YYYY"
                            time-format="HH:mm"
                            style="width: 300px;"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="11">
                    <el-form-item label="客户名称" prop="cust">
                        <el-select placeholder="请选择" style="width: 300px;" v-model="saleform.cust" @change="GetCustomerById(saleform.cust)">
                            <el-option v-for="item in customers" :key="item.cust_id" :label="item.cust_name" :value="item.cust_id"></el-option>
                        </el-select>
                        <el-button type="success" text="设置" @click="SetCustomer">设置</el-button>
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item label="联系人">
                        <el-input placeholder="请输入" style="width: 300px;" disabled v-model="saleform.custlink"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="11">
                    <el-form-item label="联系方式">
                        <el-input placeholder="请输入" style="width: 300px;" disabled v-model="saleform.custphone"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item label="销售部门" prop="dept">
                        <el-select placeholder="请选择" style="width: 300px;" v-model="saleform.dept" @change="GetUserByDeptId(saleform.dept)">
                            <el-option v-for="item in deps" :key="item.department_id" :label="item.department_name" :value="item.department_id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="11">
                    <el-form-item label="销售负责人" prop="user">
                        <el-select placeholder="请选择" style="width: 300px;" v-model="saleform.user" @change="handleUserChange">
                            <el-option v-for="item in users" :key="item.user_id" :label="item.user_name" :value="item.user_id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="20">
                    <el-form-item label="备注" prop="remark">
                        <el-input type="textarea" placeholder="请输入" v-model="saleform.remark"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>


     <!--销售货品明细-->
     <div class="white-container">
        <h3 style="text-align: left;margin-left: 20px;padding-top: 20px;">销售货品明细</h3>
        <hr style="border:1px solid #ccd0d4;"/>
        <div style="text-align: left;margin-left: 20px;">
            <el-button type="success" @click="ShowProduct">添加</el-button>
            <el-button @click="batchRemoveProducts">移除</el-button>
        </div>
        <!--表格-->
        <el-table :data="selectedProducts" stripe style="margin-top: 10px;" @selection-change="SelectChange">
            <el-table-column fixed type="selection"></el-table-column>
            <el-table-column fixed type="index" label="序号" width="100"></el-table-column>
            <el-table-column fixed prop="proc_name" label="货品名称" width="150"></el-table-column>
            <el-table-column prop="proc_code" label="货品编号" width="150"></el-table-column>
            <el-table-column prop="proc_model" label="规格型号"></el-table-column>
            <el-table-column prop="proc_primary_unit" label="单位" width="70"></el-table-column>
            <el-table-column prop="type_name" label="货品类型"></el-table-column>
            <el-table-column label="可用库存" width="100">
                <template #default="scope">
                    {{ (scope.row.proc_ky_inventory || 0) - (scope.row.proc_saled_num || 0) }}
                </template>
            </el-table-column>
            <el-table-column prop="proc_saled_num" label="销售数量" width="150">
                <template #default="scope">
                    <el-input-number v-model="scope.row.proc_saled_num" :min="1" :max="(scope.row.proc_ky_inventory || 0)" @change="calculateAmount(scope.row)" style="width: 120px;"></el-input-number>
                </template>
            </el-table-column>
            <el-table-column prop="proc_saled_price" label="销售单价" width="160">
                <template #default="scope">
                    <el-input-number v-model="scope.row.proc_saled_price" :min="0" :precision="2" @change="calculateAmount(scope.row)" style="width: 120px;"></el-input-number>
                </template>
            </el-table-column>
            <el-table-column prop="proc_saled_total" label="销售金额" width="150"></el-table-column>
            <el-table-column prop="remark" label="备注" width="150">
                <template #default="scope">
                    <el-input v-model="scope.row.remark" placeholder="备注" style="width: 120px;"></el-input>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
                <template #default="scope">
                    <el-button type="danger" size="small" text="移除" @click="removeProduct(scope.row.proc_id)">移除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 汇总信息 -->
        <div style="display: flex; justify-content: flex-end; margin-top: 15px; padding-right: 20px;">
            <div style="text-align: right;">
                <span style="margin-right: 20px;">货品种类: <b style="color: red;">{{ selectedProducts.length }}</b></span>
                <span style="margin-right: 20px;">货品数量: <b style="color: red;">{{ calculateTotalQuantity() }}</b></span>
                <span>总金额: <b style="color: red;">{{ calculateTotalAmount() }}</b></span>
            </div>
        </div>
    </div>



    <!--上传附件-->
    <div class="white-container">
        <h3 style="text-align: left;margin-left: 20px;padding-top: 20px;">上传附件</h3>
        <hr style="border:1px solid #ccd0d4;"/>
        <el-upload
            :file-list="filelist" 
            class="upload-demo"
            action="http://localhost:5194/api/PublicFile/Uploadfile"
            multiple
            name="files"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :limit="3"
            :on-exceed="handleExceed"
            :on-success="handleFileSuccess"
            :headers="headers"
            style="text-align: left;margin-left: 20px;">
            <el-button type="primary">上传附件</el-button>
                <template #tip>
                    <div class="el-upload__tip">
                        您可以上传doc, pdf, rar等格式的文件，单个文件上传最大200MB。
                    </div>
                </template>
        </el-upload>
    </div>


    <!-- 底部操作栏 -->
    <div class="action-bar">
        <el-button @click="Close">关闭</el-button>
        <el-button @click="SaveAsDraft">保存为草稿</el-button>
        <el-button type="primary" @click="OK">保存</el-button>
    </div>


    <!--展示货品信息模态框-->
    <el-dialog v-model="dialogTableVisible" title="添加货品" width="800" close-on-click-modal="false">
        <div>
            <el-form :model="procform" ref="procref" :inline="true" style="text-align: left;">
                <el-form-item label="货品名称" prop="name">
                    <el-input placeholder="请输入货品名称" v-model="procform.name"></el-input>
                </el-form-item>
                <el-form-item label="单位" prop="unit">
                    <el-select placeholder="请选择单位" v-model="procform.unit" style="width: 200px;">
                        <el-option v-for="item in units" :key="item.dict_label" :label="item.dict_label" :value="item.dict_label"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button @click="Reset">重置</el-button>
                    <el-button type="success" @click="Search">查询</el-button>
                </el-form-item>
            </el-form>
            <!--表格-->
            <el-table :data="procdata" stripe height="400" border @selection-change="handleSelectionChange" :row-class-name="tableRowClassName">
                <el-table-column type="selection" width="50" :selectable="isSelectable"></el-table-column>
                <el-table-column prop="proc_id" label="序号" width="70"></el-table-column>
                <el-table-column prop="proc_code" label="货品编号" width="150"></el-table-column>
                <el-table-column prop="proc_name" label="货品名称" width="150"></el-table-column>
                <el-table-column prop="proc_model" label="规格型号" width="120"></el-table-column>
                <el-table-column prop="proc_primary_unit" label="单位" width="80"></el-table-column>
                <el-table-column prop="instock_price" label="入库单价" width="100">
                    <template #default="scope">
                        {{ scope.row.instock_price ? Number(scope.row.instock_price).toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
                <el-table-column prop="proc_ky_inventory" label="可用库存" width="100">
                    <template #default="scope">
                        {{ scope.row.proc_ky_inventory || 0 }}
                    </template>
                </el-table-column>
            </el-table>

            <div style="display: flex; justify-content: flex-end; margin-top: 15px;">
                 <!-- 页码 -->
                <el-pagination :page-size=10 :pager-count="11" layout="prev, pager, next,jumper" :total="rows"
                    v-on:current-change="handlePageChange">
                </el-pagination>
            </div>
        </div>
        <template #footer>
            <div style="text-align: right;">
                <el-button @click="dialogTableVisible = false">取消</el-button>
                <el-button type="success" @click="confirmProductSelection">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>
  
<script>
import {ref,reactive,onMounted} from 'vue';
import http from '../auth/index';
import { ElMessage,ElMessageBox } from 'element-plus'; //提示信息
import { useRoute,useRouter} from 'vue-router';//路由
import { ArrowDown } from '@element-plus/icons-vue';

export default {
    components: {
        ArrowDown
    },
    setup(){

        const route = useRoute();//路由（获取参数）
        const router = useRouter();//路由（实现跳转）
        //当前用户信息
        const user = JSON.parse(sessionStorage.getItem("user"));

         //规则验证
         const rules = reactive({
            date:[
                { required: true, message: '请选择销售日期', trigger: 'blur' },
            ],
            cust:[
                { required: true, message: '请选择客户', trigger: 'blur' },
            ],
            dept:[
                { required: true, message: '请选择销售部门', trigger: 'blur' },
            ],
            user:[
                { required: true, message: '请选择销售负责人', trigger: 'blur' },
            ]
        });

        //日期转换格式
        function formatDateTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

        //获取到传过来的saleid和salecode
        const saleid=route.params.saleid;
        const salecode=route.params.salecode;

        //查询所有客户
        const customers=ref([]);
        function GetCustomers(){
            http.get("/Customer/GetCustomers")
            .then(res=>{
                customers.value=res.data;
            }).catch(err=>{
                console.log(err);
            })
        }

        //根据id查询客户信息并自动赋值
        function GetCustomerById(id){
            http.get("/Customer/GetIdCustomer?id="+id)
            .then(res=>{
                saleform.custname=res.data.cust_name;
                saleform.custlink=res.data.cust_linkman;
                saleform.custphone=res.data.cust_linkphone;
            }).catch(err=>{
                console.log(err);
            })
        }

        //查询所有部门
        const deps=ref([]);
        function GetDepartments(){
            http.get("/Department/GetDepartments")
            .then(res=>{
                deps.value=res.data;
            }).catch(err=>{
                console.log(err);
            })
        }

        //根据选择的部门id映射出对应的用户下拉框
        const users=ref([]);
        function GetUserByDeptId(id){
            http.get("/User/GetUserByDeptId?depid="+id)
            .then(res=>{
                users.value=res.data;
                // 设置部门名称
                const selectedDept = deps.value.find(dept => dept.department_id === id);
                if (selectedDept) {
                    saleform.deptname = selectedDept.department_name;
                }
                // 如果已经有用户ID但没有用户名，尝试从新加载的用户列表中找到对应用户名
                if (saleform.user && !saleform.username) {
                    const selectedUser = users.value.find(u => u.user_id === saleform.user);
                    if (selectedUser) {
                        saleform.username = selectedUser.user_name;
                    }
                }
            }).catch(err=>{
                console.log(err);
            })
        }

        // 当选择用户时，将用户名赋值给saleform.username
        function handleUserChange(userId) {
            const selectedUser = users.value.find(user => user.user_id === userId);
            if (selectedUser) {
                saleform.username = selectedUser.user_name;
            }
        }


        //表单信息
        const saleref=ref("");
        const saleform=reactive({
            code:"",
            date:"",
            cust:"",
            custname:"",
            custlink:"",
            custphone:"",
            dept:"",
            deptname:"",
            user:"",
            username:"",
            remark:"",
        })

        //#region 根据id获取销售单信息
        //根据id获取销售单信息
        function GetSaleById(){
            http.get("/Sale_h/GetSale_HById?id="+saleid)
            .then(res=>{
                saleform.code=res.data.sale_code;
                saleform.date=res.data.sale_date;
                saleform.cust=res.data.cust_id;
                saleform.custname=res.data.cust_name;
                saleform.custlink=res.data.cust_linkman;
                saleform.custphone=res.data.cust_linkphone;
                saleform.dept=res.data.sale_depId;
                saleform.deptname=res.data.sale_depName;
                saleform.user=res.data.sale_userId;
                saleform.username=res.data.sale_userName;
                saleform.remark=res.data.remark;
               
                // 确保部门的用户列表已加载
                if (saleform.dept) {
                    GetUserByDeptId(saleform.dept);
                }
            }).catch(err=>{
                console.log(err);
            })
        }
        
        //根据销售单id显示销售明细信息
        async function GetSaleDetailById(){
            try {
                // 1. 获取销售明细列表 
                const detailRes = await http.get("/Sale_d/GetSale_ds?saleid="+saleid);
                const detailList = detailRes.data;
                
                // 2. 为每个明细项获取完整的货品信息
                const productsWithDetails = [];
                
                for (const detail of detailList) {
                    // 2.1 获取货品详细信息
                    const productRes = await http.get(`/Product/GetProductById?id=${detail.proc_id}`);
                    if (productRes.data) {
                        const product = productRes.data;
                        
                        // 计算基础库存（当前计划库存 + 本次销售的原始数量）
                        const original_sale_quantity = detail.proc_saled_num || 0;
                        const current_planned_stock = product.proc_ky_inventory || 0;
                        const base_stock = current_planned_stock + original_sale_quantity;

                        // 2.2 合并明细与货品信息
                        productsWithDetails.push({
                            ...detail,           // 销售明细数据
                            proc_name: product.proc_name,
                            proc_code: product.proc_code,
                            proc_model: product.proc_model,
                            proc_primary_unit: product.proc_primary_unit,
                            proc_ky_inventory: base_stock, // 使用基础库存
                            type_name: product.type_name,
                            // 保留原来的销售数量和价格
                            proc_saled_num: detail.proc_saled_num,
                            proc_saled_price: detail.proc_saled_price,
                            proc_saled_total: detail.proc_saled_total,
                            remark: detail.remark || ''
                        });
                    }
                }
                // 3. 更新显示数据
                selectedProducts.value = productsWithDetails;
                
            } catch (err) {
                console.error("获取销售明细失败:", err);
                ElMessage.error("获取销售明细信息失败，请刷新重试");
            }
        }

        //查询货品附件
        function GetSaleFileByCode(){
            http.get("/PublicFile/GetPublicFileBy?type=销售单&code="+salecode)
            .then(res=>{
                console.log(res.data)
                filelist.value=res.data.map(item=>{
                    return {
                        name: item.title,
                        url:item.file_name,
                        originalName:item.title
                    }
                })
            })
        }
        //#endregion
        
        //#region 上传附件
        const filelist = ref([])
        //头部带token
        const token=sessionStorage.getItem('token');
        const headers = {
             Authorization: `Bearer ${token}`, // 添加 token 到请求头
        };
        // 上传成功回调方法
        function handleFileSuccess(response, file, fileList) {
            if (Array.isArray(response)) {
                // 创建 { 文件名: URL } 的映射
                const urlMap = response.reduce((map, res) => {
                    if (res.success) map[res.originalName] = res.path;
                    return map;
                }, {});
                
                // 更新文件列表
                filelist.value = fileList.map(item => ({
                    ...item,
                    url: urlMap[item.name] || item.url,  // 优先使用新URL
                    status: urlMap[item.name] ? 'success' : item.status,
                    originalName: item.originalName || item.name
                }));
            }
        }
        //预览
        function handlePreview(file){
            if (!file.url) {
                ElMessage.error('文件URL不存在，请重新上传');
                return;
            }
            const ext = file.name.split('.').pop().toLowerCase();
            
            switch (ext) {
                case 'jpg': case 'jpeg': case 'png': case 'gif': case 'bmp':
                    window.open(file.url, '_blank');
                    break;
                case 'pdf':
                    window.open(file.url, '_blank');
                    break;
                case 'doc': case 'docx': case 'xls': case 'xlsx': case 'ppt': case 'pptx':
                    window.open(file.url, '_blank');
                    break;
                default:
                    // 下载其他格式文件
                    const link = document.createElement('a');
                    link.href = file.url;
                    link.download = file.name;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
            }
        };

        //移除附件
        function handleRemove(file, fileList) {
            filelist.value = fileList;
        }
        //#endregion

        //#region 展示货品信息
        //查询所有单位
        const units=ref([]);
        function Getunit(){
            http.get("/DictData/GetAllDictDataBytype?typeid=8")
            .then(res=>{
                units.value=res.data;
            }).catch(err=>{
                console.log(err);
            })
        }
        
        function isSelectable(row) {
            return row.proc_ky_inventory && row.proc_ky_inventory > 0;
        }

        function tableRowClassName({ row }) {
            if (!row.proc_ky_inventory || row.proc_ky_inventory <= 0) {
                return 'warning-row';
            }
            return '';
        }
        
        //模态框
        const dialogTableVisible=ref(false);
        function ShowProduct(){
            dialogTableVisible.value=true;
        }
        const procref=ref("");
        const procform=reactive({
            name:"",
            unit:"",
        })
        //表格数据
        const procdata = ref([]);
        //总数据量
        const rows = ref(0);
        //当前页
        const currentPage = ref(1);

        //重置
        function Reset(){
            procref.value?.resetFields();
            procform.name = "";
            procform.unit = "";
        }

         //查询
         function Search() {
            All();
        }

        //查询数据
        function All(){
            http.get("/Product/GetAdvancedProduct", {
                params: {
                    code:"",
                    name:procform.name,
                    typeid:"",
                    model:"",
                    unit:procform.unit,
                    startinprice:"",
                    endinprice:"",
                    startoutprice:"",
                    endoutprice:"",
                    is_datamanagement:"",
                    startwarningdays:"",
                    endwarningdays:"",
                    status:"",
                    barcode:"",
                    whid:"",
                    starttime:"",
                    endtime:"",
                    createname:"",
                    CurrentPage:currentPage.value
                }
            }).then(res => {
                rows.value = res.data.rows;//总量
                if (res.data.list.length == 0) {
                    ElMessage({
                        message: '没有相关数据.',
                        type: 'warning',
                    })
                }
                procdata.value = res.data.list;
            }).catch(err => {
                console.log(err)
            })
        }

        // 页码改变
        function handlePageChange(val) {
            currentPage.value = val;
            All();
        }

        // 选中的产品数组
        const selectedProducts = ref([]);
        // 当前选中的行
        const multipleSelection = ref([]);
        
        // 处理表格行选择变化
        function handleSelectionChange(selection) {
            multipleSelection.value = selection;
        }
        
        // 添加产品到已选清单
        function confirmProductSelection() {
            if(multipleSelection.value.length === 0) {
                ElMessage.warning('请至少选择一个产品');
                return;
            }
            
            // 为每个选中的产品添加必要的字段
            multipleSelection.value.forEach(item => {
                // 检查是否已经添加过该产品
                const existingIndex = selectedProducts.value.findIndex(p => p.proc_id === item.proc_id);
                
                if(existingIndex === -1) {
                    // 添加新产品
                    const newItem = {
                        ...item,
                        proc_saled_num: 1,
                        proc_saled_price: item.instock_price || 0,
                        proc_saled_total: item.instock_price || 0,
                        remark: ''
                    };
                    selectedProducts.value.push(newItem);
                    calculateAmount(newItem);
                } else {
                    // 已存在则更新数量
                    selectedProducts.value[existingIndex].proc_saled_num += 1;
                    calculateAmount(selectedProducts.value[existingIndex]);
                }
            });
            
            dialogTableVisible.value = false;
        }
        
        // 计算金额
        function calculateAmount(row) {
            if (row.proc_saled_num > row.proc_ky_inventory) {
                ElMessage.warning('销售数量不能超过当前库存');
                row.proc_saled_num = row.proc_ky_inventory;
            }
            // 确保销售数量和单价都存在
            if (row.proc_saled_num && row.proc_saled_price) {
                // 计算金额，并保留两位小数
                row.proc_saled_total = (row.proc_saled_num * row.proc_saled_price).toFixed(2);
            } else {
                row.proc_saled_total = '0.00';
            }
        }
        
        // 计算总数量
        function calculateTotalQuantity() {
            if (selectedProducts.value.length === 0) return 0;
            return selectedProducts.value.reduce((total, product) => {
                return total + (product.proc_saled_num || 0);
            }, 0);
        }
        
        // 计算总金额
        function calculateTotalAmount() {
            if (selectedProducts.value.length === 0) return '0.00';
            const total = selectedProducts.value.reduce((sum, product) => {
                return sum + (parseFloat(product.proc_saled_total) || 0);
            }, 0);
            return total.toFixed(2);
        }
        
        // 移除产品
        async function removeProduct(procId) {
            const index = selectedProducts.value.findIndex(item => item.proc_id === procId);
            if (index !== -1) {
                const item = selectedProducts.value[index];
                // 查数据库最新库存
                const productRes = await http.get(`/Product/GetProductById?id=${item.proc_id}`);
                const dbInventory = productRes.data.proc_ky_inventory || 0;
                // 加回本次销售数量
                const newInventory = dbInventory + (item.proc_saled_num || 0);
                await http.put(`/Product/Updateky?id=${item.proc_id}&inventory=${newInventory}`);
                selectedProducts.value.splice(index, 1);
            }
        }

        const selectdata=ref([]);//选中数据
        //获取选中数据
        function SelectChange(val){
            selectdata.value=val;
        }
        //批量移除
        async function batchRemoveProducts(){
            if(selectdata.value.length===0){
                ElMessage.warning('请先选择要移除的货品');
                return;
            }
            for(const item of selectdata.value){
                const index=selectedProducts.value.findIndex(p=>p.proc_id===item.proc_id);
                if(index!==-1){
                    // 查数据库最新库存
                    const productRes = await http.get(`/Product/GetProductById?id=${item.proc_id}`);
                    const dbInventory = productRes.data.proc_ky_inventory || 0;
                    // 加回本次销售数量
                    const newInventory = dbInventory + (item.proc_saled_num || 0);
                    await http.put(`/Product/Updateky?id=${item.proc_id}&inventory=${newInventory}`);
                    selectedProducts.value.splice(index,1);
                }
            }
            ElMessage.success('已移除'+selectdata.value.length+'个货品');
        }
        //#endregion

        //#region 修改
        async function Update(status = 2) { //默认待审核
            try {
                // 1. 验证表单
                const [saleValid] = await Promise.all([
                    new Promise(resolve => saleref.value.validate(resolve)),
                ]);
                if (!saleValid) {
                    return false;
                }

                // 2. 验证必须有货品信息
                if(selectedProducts.value.length === 0) {
                    ElMessage.error('请至少添加一个货品到销售明细');
                    return false;
                }

                // 3. 准备销售单主数据
                const saledata = {
                    sale_id: saleid,
                    sale_date: saleform.date,
                    cust_id: saleform.cust,
                    cust_name: saleform.custname,
                    cust_linkman: saleform.custlink,
                    cust_linkphone: saleform.custphone,
                    sale_depId: saleform.dept,
                    sale_depName: saleform.deptname,
                    sale_userId: saleform.user,
                    sale_userName: saleform.username,
                    sale_categories: selectedProducts.value.length,
                    sale_num: calculateTotalQuantity(),
                    sale_total: calculateTotalAmount(),
                    sale_status: status,
                    update_name: user.name,
                    update_time: formatDateTime(new Date()),
                    remark: saleform.remark
                }

                //执行修改
                await http.put("/Sale_h/UpdateSale_h", saledata);
                //先执行删除明细
                await http.delete("/Sale_d/DeleteSale_d?saleid="+saleid); 
                //销售明细单数据
                for(const item of selectedProducts.value) {
                    const saledetaildata = {
                        sale_id: saleid,
                        proc_id: item.proc_id,
                        proc_name: item.proc_name,
                        proc_saled_num: item.proc_saled_num,
                        proc_saled_price: item.proc_saled_price,
                        proc_saled_total: item.proc_saled_total,
                        remark: item.remark || ''
                    };
                    // 添加销售明细
                    await http.post("/Sale_d/AddSale_d", saledetaildata);

                    //更新计划可用库存
                    await http.put(`/Product/Updateky?id=${item.proc_id}&inventory=${(item.proc_ky_inventory || 0) - (item.proc_saled_num || 0)}`);
                }
                
                //4.附件上传
                //先执行删除
                await http.delete("/PublicFile/DeleteFile?type=销售单&code=" + salecode);
                console.log(filelist.value);
                //在执行添加
                if (filelist.value.length > 0) {
                    filelist.value.forEach(file => {
                        http.post("/PublicFile/AddFile?type=销售单&code=" + salecode + "&file=" + file.url+"&title="+file.originalName)
                    });
                }

                ElMessage.success('修改成功');
                return true;
            } catch (err) {
                console.log(err);
                ElMessage.error('操作失败');
                return false;
            }
        } 
        //#endregion

        
        //保存
        async function OK() {
            const result = await Update(2);//默认待审核
            if (result) {
                router.push("../../sale");
            }
        }

        //保存为草稿
        async function SaveAsDraft(){
            const result = await Update(1);//草稿
            if (result) {
                router.push("../../sale");
            }
        }


        //跳转到客户添加页面
        function SetCustomer(){
            router.push("customernew");
        }

        //关闭
        function Close(){
            router.back();
        }

        //挂载
        onMounted(() => {
           Getunit();
           All();
           GetCustomers();
           GetDepartments();
           GetSaleById();
           GetSaleDetailById();
           GetSaleFileByCode();
        });

        return{
            rules,
            Update,
            OK,
            Close,
            SaveAsDraft,
            handleFileSuccess,
            handlePreview,
            headers,
            filelist,
            ShowProduct,
            dialogTableVisible,
            procref,
            procform,
            procdata,
            rows,
            currentPage,
            Reset,
            units,
            Search,
            handlePageChange,
            confirmProductSelection,
            saleform,
            saleref,
            customers,
            GetCustomerById,
            deps,
            users,
            GetUserByDeptId,
            handleUserChange,
            selectedProducts,
            handleSelectionChange,
            removeProduct,
            calculateAmount,
            calculateTotalQuantity,
            calculateTotalAmount,
            SetCustomer,
            SelectChange,
            batchRemoveProducts,
            selectdata,
            handleRemove,
            isSelectable,
            tableRowClassName
        }
    }
}
</script>
  
<style scoped>
    /* 白色圆角容器 - 核心样式 */
    .white-container {
        background: white;
        border-radius: 12px;
        margin-bottom: 50px;
        box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
        width: 75%;
    }

    /* 底部操作栏自适应 */
    .action-bar {
        position: fixed;
        bottom: 0;
        right: 0.5%; /* 与表单右侧对齐 */
        left: 210px; /* 与菜单栏宽度一致 */
        background: white;
        border-top: 1px solid #e6e6e6;
        padding: 15px;
        text-align: right;
    }

    /* 模态框样式 */
    :deep(.el-dialog__body) {
        padding: 10px 20px;
    }
    
    :deep(.el-dialog__footer) {
        border-top: 1px solid #e6e6e6;
        padding: 10px 0;
    }
    
    :deep(.el-dialog__header) {
        border-bottom: 1px solid #e6e6e6;
    }

    :deep(.el-table .warning-row) {
        background: #fef0f0 !important;
    }

    :deep(.el-table .warning-row > td) {
        background: #fef0f0 !important;
    }
</style>